import React from "react";
import { AppBar, Toolbar, Typography } from "@mui/material";
import { withRouter } from 'react-router-dom'; 
import "./styles.css";
import axios from 'axios';
/**
 * Define TopBar, a React component of CS142 Project 5.
 */
class TopBar extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    const url = window.location.href;
    const parts = url.split('/');
    const id = parts[parts.length - 1];
    async function fetchData(url){
      try{
        const data = await axios.get(url);
        return {data: data.data};
      }catch(error){
        console.error("There was an error fetching the data:", error);
      }
    }
    const name = fetchData(`/user/${id}`);
    //const name = window.cs142models.userModel(id);
    const part = parts[parts.length - 2];
    let contents = "";
    if (part === "users"){
      contents = name.first_name + " " + name.last_name;
    }else if (part === "photos"){
      contents = "Photo of" + name.first_name + " " + name.last_name;
    }
    const version = fetchData("/test/info"); 
    //const version = window.cs142models.schemaInfo();
    const vers = "Version:" + " " + version.__v;
    return (
      <AppBar className="cs142-topbar-appBar" position="absolute">
        <Toolbar>
          <Typography variant="h5" color="inherit">
            Wang Lingling 
          </Typography>
          <Typography style={{fontSize:"30px", marginLeft: "50%", display: "inline-block", width: "100%"}} >
            {contents}
          </Typography>
          <Typography style={{fontSize:"20px", textAlign:"right", display: "inline-block", width: "100%"}} >
            {vers}
          </Typography>
        </Toolbar>
      </AppBar>
    );
  }
}

export default withRouter(TopBar);
